/**
 * Created by caosh on 2018/5/7 0007.
 */
var LayerPlugin = {};
LayerPlugin.install = function (Vue, options) {

    Vue.useLayerElement = function () {
        layui.use('element', function(){
            var element = layui.element;
        });
    }

    Vue.useLayerDate = function (elementIds, search) {
        layui.use('laydate', function(){
            var laydate = layui.laydate;

            for (var i=0, len=elementIds.length; i<len; i++) {
                var id = elementIds[i],
                    elemId = '#' + id;
                // 此处使用闭包构建多个laydate组件
                (function(elemId, id, search){
                    laydate.render({
                        elem: elemId //指定元素
                        ,done: function(value, date, endDate) {
                            // document.getElementById(id).value = value;
                            search[id] = value;
                        }
                    })
                })(elemId, id, search);
            }

        });
    }

    Vue.useLayerPage = function (elemId, paginator, search) {
        layui.use('laypage', function(){
            var laypage = layui.laypage;

            //执行一个laypage实例
            laypage.render({
                elem: elemId //注意，这里的 elemId 是 ID，不用加 # 号
                ,count: paginator.totalNum //数据总数，从服务端得到
                ,limit: paginator.pageSize
                ,curr: paginator.pageNo
                ,layout:['prev', 'page', 'next', 'skip']
                ,jump: function (obj, first) {
                    search.pageNo = obj.curr;
                    search.pageSize = obj.limit;
                }
            });
        });
    }

    Vue.useSimpleLayerPage = function (elemId, paginator, search) {
        layui.use('laypage', function(){
            var laypage = layui.laypage;

            //执行一个laypage实例
            laypage.render({
                elem: elemId //注意，这里的 elemId 是 ID，不用加 # 号
                ,count: paginator.totalNum //数据总数，从服务端得到
                ,limit: paginator.pageSize
                ,curr: paginator.pageNo
                ,layout:['prev', 'next']
                ,jump: function (obj, first) {
                    search.pageNo = obj.curr;
                    search.pageSize = obj.limit;
                }
            });
        });
    }

    Vue.useLayerForm = function (callback) {
        layui.use('form', function() {
            var form = layui.form;
            form.render();
            if (callback && typeof callback == 'function') {
                callback(form);
            }
        });
    }
    
    Vue.useLayerUpload= function (elementIds, url) {
        layui.use('upload', function(){
            var upload = layui.upload;

            for (var i=0, len=elementIds.length; i<len; i++) {
                var id = elementIds[i],
                    elemId = '#' + id;
                // 此处使用闭包构建多个laydate组件
                (function(elemId, url){
                    upload.render({
                        'elem': elemId //绑定元素
                        ,'url': url //上传接口
                        ,done: function(res){
                        }
                        ,error: function(){
                        }
                    });
                })(elemId, url);
            }

        });
    }
};

var StorePlugin = {};
StorePlugin.install = function (Vue, options) {
    Vue.saveStore = function (key, data) {
        store.set(key, data);
    }

    Vue.saveToken = function (data) {
        data.time = (new Date()).getTime();
        this.saveStore('token', data);
    }
    
    Vue.doGetAccessToken = function () {
        var _this = this,
            userinfo = _this.getStore('userinfo');

        if (userinfo == null) {
            return;
        }

        $.ajax({
            url: '/getAccessToken',
            async: false,
            type: 'post',
            dataType: 'json',
            data: {'loginName':userinfo.loginName, 'password': userinfo.password}
        }).done(function(result, status, jqXHR) {
            console.log(result, status, jqXHR);
            // 登录成功
            if (result.retCode == 0) {
                // 暂存缓存
                _this.saveToken(result.data);
            } else { // 登录失败
                console.log('获取token失败！');
            }
        }).fail(function (result, status, jqXHR) {
            console.log('请求token操作失败！');
        });
    }
    
    Vue.getToken = function () {
        var token = this.getStore('token'),
            t = (new Date()).getTime(),
            accessToken = '';
        if (!token || token.expiresIn * 1000+token.time > t) {
            this.doGetAccessToken();
            accessToken = this.getStore('token').accessToken;
        } else {
            accessToken = token.accessToken
        }

        return accessToken;
    }

    Vue.getStore = function (key) {
        return store.get(key);
    }
};


var LocationPlugin = {};
LocationPlugin.install = function (Vue, options) {
    Vue.getUrlParam = function (key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }
}


Vue.use(LayerPlugin);
Vue.use(StorePlugin);
var StatusMixin = {
    data: {
        status: {
            startDateClassObj: {
                isActive: false,
                isFinish: false,
                isError: false
            },
            endDateClassObj: {
                isActive: false,
                isFinish: false,
                isError: false
            },
            userClassObj: {
                isActive: false,
                isFinish: false,
                isError: false,
                isDefault: false
            },
            loginNameClassObj: {
                isActive: false,
                isFinish: false,
                isError: false,
                isDefault: false
            },
            passwordClassObj: {
                isActive: false,
                isFinish: false,
                isError: false,
                isDefault: false
            },
            roleNameClassObj: {
                isActive: false,
                isFinish: false,
                isError: false,
                isDefault: false
            },
            empl: {
                edit: {
                    loginName: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    emplName: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    pwd: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    roleId: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    }
                },
                add: {
                    loginName: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    emplName: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    pwd: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    },
                    roleId: {
                        isActive: false,
                        isFinish: false,
                        isError: false
                    }
                }
            },
            template: {
                tempName: {
                    isActive: false,
                    isFinish: false,
                    isError: false
                },
                payees: {
                    isActive: false,
                    isFinish: false,
                    isError: false
                }
            }
        }
    },
    methods: {
        changeStatus: function (objKeys, status) {
            var classObj = null;
            for (var i=0, l=objKeys.length; i<l; i++) {
                if (classObj) {
                    classObj = classObj[objKeys[i]];
                } else {
                    classObj = this.status[objKeys[i]];
                }
            }

            for (var k in classObj) {
                if (k == status) classObj[k]=true;
                else classObj[k]=false;
            }
        },
        resetClassObj: function (objKeys) {
            var classObj = null;
            for (var i=0, l=objKeys.length; i<l; i++) {
                if (classObj) {
                    classObj = classObj[objKeys[i]];
                } else {
                    classObj = this.status[objKeys[i]];
                }
            }

            for (var k in classObj) {
                /*if (k == 'isDefault') classObj[k]=true;
                else classObj[k]=false;*/
                classObj[k]=false;
            }
        }
    }
}


var AjaxMixin = {
    data: {
        requestDatas: {
            'token': ''
            , 'timestamp': 0
            , 'data': null
        }
        , ajaxOptions: {
            url: '',
            type: 'post',
            dataType: 'json',
            data: null,
            done: null
        }
    }
    , methods: {
        setRequestDatas: function (data) {
            this.requestDatas.token = Vue.getToken();
            this.requestDatas.timestamp = (new Date()).getTime();
            this.requestDatas.data = data;
            /*if (data && typeof data == 'object') {
                this.requestDatas.data = JSON.stringify(data);
            }*/
        },
        doLogout: function () {
            this.setRequestDatas();
            this.ajaxOptions.url = '/logout';
            this.ajaxOptions.data = this.requestDatas;
            this.ajaxOptions.done = function (result, status, jqXHR) {
                if (result.retCode == 0) {
                    console.log('退出成功');
                    window.location.href = '../login.html';
                }
            };

            this.doAjax();
        },
        doAjax: function () {
            var _this = this;
            $.ajax({
                url: _this.ajaxOptions.url,
                type: _this.ajaxOptions.type,
                dataType: _this.ajaxOptions.dataType,
                data: JSON.stringify(_this.ajaxOptions.data)
            }).done(_this.ajaxOptions.done);
        },
        setAjaxOptions: function (url, data, done) {
            this.setRequestDatas(data);
            this.ajaxOptions.url = url;
            this.ajaxOptions.data = this.requestDatas;
            this.ajaxOptions.done = done;
        }
    }
}

var UserMixin = {
    data: {
        userinfo: {
            loginName: '',
            password: ''
        }
    },
    mounted: function () {
        this.userinfo = Vue.getStore('userinfo');
        if (this.userinfo == null) {
            userinfo = {
                loginName: '',
                password: ''
            };

        }
    }
}